package com.sikong.caffine;

import com.github.benmanes.caffeine.cache.Cache;
import com.sikong.caffine.CacheInstance;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import static org.junit.Assert.*;

@Slf4j
public class Caffine {
    final String tag1 = "c1";
    final String tag2 = "c2";
    final String salt = "k";

    @Test
    public void putAndGet() {
        Cache<String, String> cache = CacheInstance.getInstance().cache;
        cache.put(tag1, tag1);
        assertEquals(cache.getIfPresent(tag1), tag1);
        assertEquals(cache.get(tag1, (salt) -> addSalt(salt, tag1)), tag1);
        cache.invalidate(tag1);
        assertNull(cache.getIfPresent(tag1));

        cache.put(tag2, tag2);
        assertNull(cache.getIfPresent(tag1));
        assertEquals(cache.get(tag1, (tag1) -> addSalt(salt, tag1)), addSalt(salt, tag1));
        assertEquals(cache.getIfPresent(tag1), addSalt(salt, tag1));
        cache.invalidate(tag1);
        cache.invalidate(tag2);
        assertNull(cache.getIfPresent(tag1));
        assertNull(cache.getIfPresent(tag2));
    }

    public String addSalt(String salt, String tag) {
        return String.format("%s%s", salt, tag);
    }

}
